package com.leha.mp.api.controller;
import com.github.pagehelper.PageInfo;
import com.leha.mp.api.form.CaseForm;
import com.leha.mp.core.Utils.Page;
import com.leha.mp.core.Utils.SmsUtil;
import com.leha.mp.core.entity.vo.UserLoginVO;
import com.leha.mp.core.services.*;
import constants.APIErrorDict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import utils.APIResult;
import utils.ValidCodeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.QueryParam;
import java.util.Date;

@RestController
@Api(value = "/user", description = "用户相关API类")
@RequestMapping("/user")
@ResponseStatus(HttpStatus.OK)

public class UserController {
    @Autowired
    private AppUserService userServices;
    @Autowired
    private ErrorMessageServices errorMessageServices;
    @Autowired
    private ConfluenceServices confluenceServices;
    @Autowired
    private BedgeServices bedgeServices;
    @Autowired
    private OrderServices orderServices;

    @RequestMapping(value = "/{uid}/update", method = {RequestMethod.POST})
    @ApiOperation(value = "上传用户资料_用户端", notes = "传输用户资料")
    APIResult login(@FormParam(value = "sessionKey") String sessionKey,
                    @FormParam(value = "encryptedData") String encryptedData,
                    @FormParam(value = "iv") String iv,
                    @PathVariable(value = "uid") Integer uid) {

        UserLoginVO loginUser = userServices.SaveInfo(1, uid, sessionKey, encryptedData, iv);
        if (loginUser == null) {
            return new APIResult(errorMessageServices.getLastError());
        } else {
            return new APIResult(loginUser);
        }
    }

    @RequestMapping(value = "/enter", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "登录_用户端", notes = "直接传code，后台获取openid，匹配对应UID")
    APIResult loginV2(@QueryParam(value="code") String code) {
        if (code == null) {
            return new APIResult(APIErrorDict.PARAMERROR);
        }
        UserLoginVO loginUser = userServices.Enter(1, code);
        if (loginUser == null) {
            return new APIResult(errorMessageServices.getLastError());
        } else {
            return new APIResult(loginUser);
        }
    }

    @RequestMapping(value = "/getInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "跟新信息_用户端", notes = "同Enter接口，刷新数据用")
    APIResult F5fresh(@QueryParam(value="uid") Integer userId) {
        if (userId == null || userId==0) {
            return new APIResult(APIErrorDict.PARAMERROR);
        }
        UserLoginVO loginUser = userServices.GetUserInfo(userId);
        if (loginUser == null) {
            return new APIResult(errorMessageServices.getLastError());
        } else {
            return new APIResult(loginUser);
        }
    }

    @RequestMapping(value = "/{phone}/verify", method = {RequestMethod.GET})
    @ApiOperation(value = "获取验证码_用户端", notes = "Get提交手机号")
    APIResult getVerify(@PathVariable String phone ,HttpServletRequest request) {
        if (phone.isEmpty()) {
            return new APIResult(APIErrorDict.PARAMERROR);
        }
        //获取6位随机数作为验证码
        String code = ValidCodeUtils.getRandNum(4);
        String context = "您的手机验证码为:" + code;
        request.getSession().getServletContext().setAttribute(phone + "code", code);
        request.getSession().getServletContext().setAttribute(phone + "codetime", System.currentTimeMillis());
        return new APIResult(SmsUtil.send(phone, context));
    }

    @RequestMapping(value = "/{uid}/{phone}/verify", method = {RequestMethod.POST})
    @ApiOperation(value = "验证码_用户端", notes = "提交收到的验证码")
    APIResult verifyPhone(@PathVariable Integer uid,
                          @PathVariable String phone,
                          @FormParam(value = "code")String code, HttpServletRequest request) {
        if (phone == null) {
            return new APIResult(APIErrorDict.PARAMERROR);
        }
        // 校验验证码是否正确
        if(!verifyValidcode(phone, code, request)) {
            return new APIResult(APIErrorDict.VerifyCodeInvalid);
        }

        userServices.SavePhone(uid, phone);
        return new APIResult("OK");
    }

    @PostMapping("/case")
    @ApiOperation(value="提交病例_用户端")
    APIResult saveCase(CaseForm caseForm) {
        if(userServices.saveCase(caseForm.toDateModel())) {
            return new APIResult("OK");
        } else {
            return new APIResult(errorMessageServices.getLastError());
        }
    }

    @GetMapping("/enterRoom")
    @ApiOperation(value="进入房间_用户端")
    APIResult enterRoom(@QueryParam(value="consultingId") Integer consultingId) {
        return new APIResult(confluenceServices.userEnterRtcRoom(consultingId));
    }

    @GetMapping("/videoRooms")
    @ApiOperation(value="获取房间列表_用户端")
    APIResult getRoomList(Integer uid) {
        return new APIResult(confluenceServices.getRoomList(uid));
    }

    @GetMapping("/myConsulting")
    @ApiOperation(value="我的诊疗记录_用户端,type0所有1图文2语音3视频,4(语音+视频)，status0所有1已支付2已接受3进行中4已完成5已关闭,多个状态用逗号,隔开")
    APIResult getMyConsulting(Integer uid, Page page, Integer type, String status) {
        return new APIResult(confluenceServices.getUserConsulting(uid, page, type, status));
    }
    /**
     * 校验验证码是否正确
     * @param code
     * @param request
     * @return
     */
    private boolean verifyValidcode(String mobile, String code, HttpServletRequest request) {
        //取出session中保存的验证码获取时间
        Long lastTime = (Long)request.getSession().getServletContext().getAttribute(mobile + "codetime");
        if(lastTime == null){
            return false;
        }

        //系统当前时间与验证码获取时间进行比较，查看验证码是否超过30s
        if(!ValidCodeUtils.ValidTimeCheck(System.currentTimeMillis(), lastTime)){
            return false;
        }
        //获取session中的验证码，比较客户端提交的验证码和生成的验证码
        String sysCode = (String)request.getSession().getServletContext().getAttribute(mobile + "code");
        if(!sysCode.equals(code)){
            return false;
        }
        request.getSession().getServletContext().removeAttribute(mobile + "code");
        return true;
    }

    @GetMapping("/{userId}/myOrder")
    @ApiOperation("我的订单_用户端, -1 所有 0待支付，1已完成，2已取消，3，已退款")
    public APIResult getUserOrder(@PathVariable Integer userId, Page page, Integer type) {
        return new APIResult(new PageInfo(userServices.getUserOrders(userId, type, page)));
    }

    @GetMapping("/{userId}/myDoctor")
    @ApiOperation("我的医生_用户端")
    public APIResult getMyDoctor(@PathVariable Integer userId){
        return new APIResult(userServices.getMyDoctor(userId));
    }

    @GetMapping("/{consutingId}/evaluate")
    @ApiOperation("获取评价内容")
    public APIResult getMyConsuting(@PathVariable Integer consutingId, Integer userId) {
        return new APIResult(userServices.getMyEvaluate(consutingId, userId));
    }

    @GetMapping("/{userId}/myVipDoctor")
    @ApiOperation("我的私人医生")
    public APIResult getMyVip(@PathVariable Integer userId) {
        return new APIResult(userServices.getMyVipDoctor(userId));
    }

    @PostMapping("cancelConsulting")
    @ApiOperation("取消咨询_用户端接口")
    public APIResult cancelConsulting(Integer consultingId) {
        return new APIResult(orderServices.cancelConsultingByUser(consultingId));
    }
}
